﻿using System;

namespace VPLink.WebParts
{
    public class XSLUtilities
    {
        public string FormatLink(string url)
        {
            if (url.IndexOf(",") >= 0) url = url.Substring(0, url.IndexOf(","));
            return url;
        }

        public string GetDescription(string url)
        {
            if (url.IndexOf(", ") >= 0) url = url.Substring(url.IndexOf(", ") + 2);
            return url;
        }

        public string FormatPicture(string url)
        {
            if (url.IndexOf(",") >= 0) url = url.Substring(0, url.IndexOf(","));
            return url;
        }

        public string FormatAuthor(string url)
        {
            if (url.IndexOf(";#") >= 0) url = url.Substring(url.IndexOf(";#") + 2);
            return url;
        }

        public string FormatDate(string url)
        {
            DateTime dt = DateTime.Parse(url);
            //return dt.ToString("d/M/yyyy h:mm");
            return dt.ToString("dd/MM/yyyy");
        }

        public string FormatBody(string url)
        {
            //url = Regex.Replace(url, "<[^>]*>", string.Empty);
            if (url.Length > 250)
            {
                int pos = url.IndexOf(" ", 250);
                if (pos > -1)
                {
                    string sub = url.Substring(0, pos) + "...";
                    int count = CountString(sub, "\r\n");
                    if (count > 3) return sub.Substring(0, StringPos(sub, "\r\n", 3));
                    else return sub;
                }
                else return url;
            }
            else return url;
        }

        public string FormatTitle(string url)
        {
            return url.ToUpper()[0] + url.Substring(1);
        }

        public string GetMediaType(string url)
        {
            if (url.IndexOf(",") >= 0) url = url.Substring(0, url.IndexOf(","));
            url = url.Substring(url.LastIndexOf(".") + 1).Trim().ToLower();
            if (url == "flv") return "video";
            else if (url == "jpg" || url == "jpeg" || url == "gif" || url == "png" || url == "bmp") return "picture";
            else return "other";
        }

        private int CountString(string input, string value)
        {
            int pos = 0;
            int count = 0;
            while ((pos = input.IndexOf(value, pos)) > -1)
            {
                count++;
                pos += value.Length;
            }
            return count;
        }

        private int StringPos(string input, string value, int limit)
        {
            int pos = 0;
            int count = 0;
            while ((pos = input.IndexOf(value, pos)) > -1)
            {
                count++;
                if (count == limit) break;
                pos += value.Length;
            }
            return pos;
        }
    }
}
